package com.example.safelib.fragment


import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.fragment.app.Fragment
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.example.baselib.dialog.MsgDialog
import com.example.baselib.fragment.BaseFragment

import com.example.safelib.R
import com.example.safelib.SafeViewModel
import com.example.safelib.adapter.SafeAlarmAdapter
import com.example.safelib.adapter.SafeListAdapter
import com.example.safelib.bean.SafeSenSorBean
import kotlinx.android.synthetic.main.fragment_safe_alarm.*
import kotlinx.android.synthetic.main.fragment_safe_line.*
import kotlinx.android.synthetic.main.fragment_safe_list.*
import java.lang.Exception

/**
 * A simple [Fragment] subclass.
 */
class SafeListFragment : BaseFragment<SafeViewModel>() {
    private lateinit var pvSensor: OptionsPickerView<Any>
    private var allSensorList: List<SafeSenSorBean> = ArrayList<SafeSenSorBean>()
    private lateinit var senTypeList: ArrayList<String>
    private lateinit var senNameList: ArrayList<List<String>>
    private val safeListAdapter: SafeListAdapter by lazy { SafeListAdapter(R.layout.safe_list_item) }
    override fun providerVMClass(): Class<SafeViewModel>? {
        return SafeViewModel::class.java
    }

    override fun contentLayout(): Int {
        return R.layout.fragment_safe_list
    }

    override fun initView() {
        initSensorPicker()
        val empty = LayoutInflater.from(context).inflate(R.layout.empty_item, null, false)
        safeListAdapter.emptyView = empty
        safe_list_rcy.adapter = safeListAdapter
        safe_list_rcy.layoutManager =
            LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        safe_list_srl.setOnRefreshListener {
            viewModel.isLoad = false
            viewModel.loadSenInfo()
        }
        safe_list_sensor.setOnClickListener { pvSensor.show() }
        if (viewModel.senType.isNotEmpty()) safe_list_sensor.text= viewModel.senType
        safeListAdapter.setOnItemClickListener { adapter, view, position ->
            val sorBean = adapter.getItem(position) as SafeSenSorBean
            val bundle =Bundle()
            bundle.putString("sensornum",sorBean.sensornum)
            Navigation.findNavController(view).navigate(R.id.action_menu_safe_list_to_safeSensorInfoFragment,bundle)
        }
    }
    override fun initData() {
        viewModel.loadSenList()

        viewModel.getSenList().observe(this, Observer {
            senTypeList = ArrayList()
            senTypeList.add("模拟量")
            senTypeList.add("开关量")
            senTypeList.add("状态量")
            val Temp1List =ArrayList<String>()
            val Temp2List =ArrayList<String>()
            val Temp3List =ArrayList<String>()
            for (ser in it.senname){
                when (ser.sensortype){
                    1-> Temp1List.add(ser.sensorname)
                    2 ->  Temp2List.add(ser.sensorname)
                    else-> Temp3List.add(ser.sensorname)
                }
            }
            senNameList= ArrayList()
            senNameList.add(Temp1List)
            senNameList.add(Temp2List)
            senNameList.add(Temp3List)
            pvSensor.setPicker(senTypeList as List<String>,senNameList as List<List<String>>)
        })
        viewModel.getSenInfo().observe(this, Observer {
            allSensorList = it
            safe_list_time.text="数据生成时间：${it[0].inserttime}"
            showSensor()
            safe_list_empty.visibility = View.INVISIBLE

        })
        if (!viewModel.getUnitInfo().isNullOrEmpty()){
            safe_list_nickname.text=viewModel.getUnitInfo()["unitname"]
        }
    }

    private fun initSensorPicker() {
        pvSensor = OptionsPickerBuilder(context,
            OnOptionsSelectListener { options1, options2, options3, v ->
                try {
                    if (senTypeList[options1].isNotEmpty()) {
                        viewModel.senType = senNameList[options1][options2]
                        safe_list_sensor.text = viewModel.senType
                        showSensor()
                    }
                } catch (e: Exception) {
                }
            })
            .isDialog(true)
            .setContentTextSize(18)
            .setLayoutRes(R.layout.pickerview_custom_nick) { v ->
                val tvTitle = v.findViewById<TextView>(R.id.picker_title)
                val submit = v.findViewById<Button>(R.id.finish_btn)
                val cancel = v.findViewById<Button>(R.id.cancel_btn)
                val rest = v.findViewById<Button>(R.id.rest_btn)
                tvTitle.text = "选择传感器类型"
                submit.setOnClickListener {
                    pvSensor.returnData()
                    pvSensor.dismiss()
                }
                cancel.setOnClickListener { pvSensor.dismiss() }
                rest.visibility=View.VISIBLE
                rest.setOnClickListener {
                    viewModel.senType =""
                    safe_list_sensor.text = "选择传感器类型"
                    showSensor()
                    pvSensor.dismiss()
                }
            }
            .setTextColorCenter(resources.getColor(R.color.colorDBlue))
            .setItemVisibleCount(9)
            .setLineSpacingMultiplier(2.6.toFloat())
            .setBackgroundId(R.color.colorBlack)
            .build()
    }

    private fun showSensor() {
        if (viewModel.senType.isNullOrEmpty()) {
            safeListAdapter.setNewData(allSensorList)
        } else {
            val showList = ArrayList<SafeSenSorBean>()
            for (sensor in allSensorList) {
                if (sensor.sensorname == viewModel.senType) showList.add(sensor)
            }
            safeListAdapter.setNewData(showList)
        }
    }

    override fun requestFinally(it: Int?) {
        super.requestFinally(it)
        safe_list_srl.isRefreshing = false
    }

    override fun requestError(it: Exception?) {
        if (it?.message=="暂无数据"){
            safe_list_empty.visibility = View.VISIBLE
            safe_list_empty.findViewById<TextView>(R.id.err_txt).text=it?.message
            safe_list_empty.findViewById<TextView>(R.id.err_msg).visibility=View.INVISIBLE
//            safe_list_empty.findViewById<ImageView>(R.id.err_img).visibility=View.INVISIBLE
        }else{
            super.requestError(it)
//            safe_list_empty.findViewById<TextView>(R.id.err_txt).text = "获取传感器信息失败"
//            safe_list_empty.findViewById<TextView>(R.id.err_msg).text = it?.message
        }

        safe_list_empty.findViewById<Button>(R.id.err_rest_btn)
            .setOnClickListener { viewModel.loadSenList()}

    }

}
